package ext.tianma.part.validators;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import wt.fc.Persistable;
import wt.fc.WTReference;
import wt.folder.SubFolder;
import wt.inf.container.WTContained;
import wt.inf.container.WTContainer;
import wt.inf.team.ContainerTeam;
import wt.inf.team.ContainerTeamHelper;
import wt.inf.team.ContainerTeamManaged;
import wt.inf.team.ContainerTeamManagedInfo;
import wt.inf.team.ContainerTeamReference;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.project.Role;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;

import com.ptc.core.ui.validation.DefaultSimpleValidationFilter;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationStatus;

public class BatchUpdateFolderPartsValidators extends DefaultSimpleValidationFilter 
{
	public BatchUpdateFolderPartsValidators(){}
	
	public UIValidationStatus preValidateAction(UIValidationKey uivalidationkey, UIValidationCriteria uivalidationcriteria)
	{
		UIValidationStatus uivalidationstatus = UIValidationStatus.HIDDEN;
		boolean bool = SessionServerHelper.manager.isAccessEnforced();
		try
		{
			SessionServerHelper.manager.setAccessEnforced(false);
			WTReference wtreference = uivalidationcriteria.getContextObject();
			if (wtreference == null)
			{
				return uivalidationstatus;
			}
			
			Persistable persistable = wtreference.getObject();
			WTPrincipal cur_user = SessionHelper.manager.getPrincipal();
			System.out.println("-----------------------persistable="+persistable+" ==========cur_user="+cur_user.getName());
			WTContained containedObj = (WTContained) persistable;
			
	    	 wt.inf.container.WTContainer container = containedObj.getContainer();
	    	
	    	String containerName=container.getName();//存储库名称
	    	
	    	System.out.println("--------------------containerName="+containerName);
	    	String[] roleKey = {"BOMEngineer"};
	    	//BOM工程师
	    	boolean bomengieer = isExistInRole(roleKey,container,cur_user.getName());
	    	
	    	//checkIsRoleMember(folder, cur_user, "BOMEngineer");
	    	System.out.println("-----------bomengieer="+bomengieer);
		    if(persistable instanceof  SubFolder)
			{
		    	
		    	SubFolder folder=(SubFolder)persistable;
		    	
				//管理员
				//boolean isadmin = checkIsAdmin((WTUser) cur_user);
				if(containerName.equals("物料库") && bomengieer)
				{
					uivalidationstatus = UIValidationStatus.ENABLED;
					return uivalidationstatus;
				}
				if(containerName.equals("二级物料库") && bomengieer)
				{
					uivalidationstatus = UIValidationStatus.ENABLED;
					return uivalidationstatus;
				}
			}
			return uivalidationstatus;
		}
		catch (WTException e)
		{
			e.printStackTrace();
			return uivalidationstatus;
		}
		finally 
    	{
    		SessionServerHelper.manager.setAccessEnforced(bool);
        }
		
	}
	/**
	 * 检查用户是否是管理员组成员
	 * 
	 * @param wtuser
	 *           用户
	 * @return 如果是管理员组成员true ；不是管理员组成员为false
	 * @exception WTException
	 */
	public static boolean checkIsAdmin(WTUser wtuser ) throws WTException
	{
		boolean flag = false;
		if(wtuser==null)
			return false;
		GenericDirectoryContextProvider genericdirectorycontextprovider = new GenericDirectoryContextProvider(null);
	     WTGroup wtgroup = OrganizationServicesHelper.manager.getGroup("Administrators", genericdirectorycontextprovider);
	     flag = wtgroup.isMember(wtuser);
		return flag;
	}
	/**
	 * 判断当前用户名是否在团队指定的角色中
	 * @param roleKey 角色名数组
	 * @param container 当前容器
	 * @param name 当前登录的用户名
	 * @return
	 */
	public static Boolean isExistInRole(String[] roleKey,WTContainer container,String name)
	{
		List list =null;
		for(int i = 0;i<roleKey.length;i++)
		{
			Role role = Role.toRole(roleKey[i]);
			if(null==role)
				continue;
			try {
				list = getAllPrincipalsForTarget(container,role);
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(null==list)
				continue;
			for(Iterator it = list.iterator();it.hasNext();)
			{
				WTPrincipalReference principalref = (WTPrincipalReference) it.next();
				System.out.println("已经存在的用户名："+principalref.getName());
				if(principalref.getName().equals(name))
				{
					return true;
				}
			}
			list =null;
		}
		return false;
	}
	
	/**
	 * 获取容器团队中某个角色的成员，此方法支持有共享团队的容器
	 * @param container
	 * @param role
	 * @return
	 * @throws WTException
	 * @author ZhiChao Yuan
	 */
	public static ArrayList getAllPrincipalsForTarget(WTContainer container, Role role) throws WTException {
		if ((container instanceof ContainerTeamManaged) && role != null) {
			ContainerTeamManaged ctm = (ContainerTeamManaged) container;
			ContainerTeamManagedInfo containerteammanagedinfo = ctm.getContainerTeamManagedInfo();
			ContainerTeam containerTeam = ContainerTeamHelper.service.getContainerTeam(ctm);
			if (containerteammanagedinfo.getSharedTeamId() != null && containerteammanagedinfo.getSharedTeamId().getKey() != null &&
			        containerteammanagedinfo.getSharedTeamId().getKey().getClassname() != null) {
				//有共享团队
				ArrayList localWtps = containerTeam.getAllPrincipalsForTarget(role);
				//System.out.println("localWtps:"+localWtps);
				ArrayList allWtps = localWtps;
				ContainerTeamReference containerTeamRef = ctm.getSharedTeamReference();
				if (containerTeamRef != null) {
					ContainerTeam sharedTeam = (ContainerTeam) containerTeamRef.getObject();
					if (sharedTeam != null) {
						ArrayList sharedWtps = sharedTeam.getAllPrincipalsForTarget(role);
						//System.out.println("sharedWtps:"+sharedWtps);
						for (int i = 0; i < sharedWtps.size(); i++) {
							WTPrincipalReference wtpRef = (WTPrincipalReference) sharedWtps.get(i);
							if (!allWtps.contains(wtpRef)) {
								allWtps.add(wtpRef);
							}
						}
					}
				}
				return allWtps;
			} else {
				//无共享团队
				return containerTeam.getAllPrincipalsForTarget(role);
			}
		} else {
			return null;
		}
	}
	
}
